# -*- coding: utf-8 -*-
# @Date：2024/9/30 11:50:00
# @Author：CJiaの青姝
# @FileName：cj_ninja
# @Editor：PyCharm2024
# @Remark：
from typing import Any, List

from django.db.models import QuerySet
from django.http import HttpRequest, JsonResponse
from ninja import NinjaAPI, Schema, Field
from ninja.types import DictStrAny
from ninja.pagination import PaginationBase
from utils.cj_jwt import DateEncoder


class CjNinjaAPI(NinjaAPI, JsonResponse):
    def create_response(
            self,
            request: HttpRequest,
            data: Any,
            *,
            status: int = 200,
            code: int = 200,
            msg: str = "操作成功🌻",
            temporal_response: JsonResponse = None,
    ) -> JsonResponse:
        std_data = {
            "code": code,
            "data": data,
            "msg": msg,
            "success": True
        }
        # 响应JSON格式
        return JsonResponse(std_data, safe=False, encoder=DateEncoder)


class MyPagination(PaginationBase):
    class Input(Schema):
        page: int = Field(1, description="当前页数", gt=-1)
        pageSize: int = Field(10, description="每页条数", gt=0)

        class Config:
            title = "分页查询参数"

    class Output(Schema):
        items: List[Any] = Field([], description="分页列表")
        total: int = Field(0, description="总数")

        class Config:
            title = "分页列表"

    def paginate_queryset(
            self,
            queryset: QuerySet,
            pagination: Input,
            **params: DictStrAny,
    ) -> Any:
        offset = pagination.pageSize * (pagination.page - 1)
        limit: int = pagination.pageSize
        return {
            "page": offset,
            "limit": limit,
            "items": queryset[offset: offset + limit],
            "total": self._items_count(queryset),
        }  # noqa: E203


class CjFilters(Schema):
    creator: str = Field(None, description="创建人", alias="creator")
    modifier: str = Field(None, description="修改人", alias="modifier")
    status: bool = Field(default=True, description="状态", alias="status")
